﻿const { SerialPort } = require('serialport');
const WebSocket = require('ws');

const portName = 'COM1'; // 修改为你的串口名称  
const baudRate = 9600; // 根据你的波特率修改  

const serialPort = new SerialPort({ path: portName, baudRate: baudRate, autoOpen: true });

serialPort.on('data', (data) => {
    console.log('Data from serial port:', data.toString());
    wss.clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
            client.send(data.toString());
        }
    });
});


const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
    console.log('New WebSocket client connected');

    ws.on('message', (message) => {
        console.log('Received message from WebSocket client:', message);
        // 如果需要，可以在这里处理来自 WebSocket 客户端的消息  
        // 例如，向串口发送数据  
        serialPort.write(message, (err) => {
            if (err) {
                return console.log('Error on write: ', err.message);
            }
            console.log('Message written to serial port');
        });
    });

    ws.on('close', () => {
        console.log('WebSocket client disconnected');
    });

    ws.on('error', (error) => {
        console.error('WebSocket error:', error);
    });
});

console.log('WebSocket server is running on ws://localhost:8080');